//
//  ScoresScene.m
//  z_boxem
//
//  Created by A B on 2/4/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ScoresScene.h"
#import "MainMenuScene.h"
#import "Score.h"
@implementation ScoresScene

+(id) scene
{
    CCScene *scene = [CCScene node];
    
    ScoresScene *layer = [ScoresScene node];
    	    [scene addChild: layer];
    
    return scene;
}

-(id) init
{
    
    if( (self=[super init] )) {
        CCLabelTTF *title = [CCLabelTTF labelWithString:@"Scores" fontName:@"Courier" fontSize:64];
        title.position =  ccp(240, 280);
        
        
        [self addChild: title];
        
        CCLayer *menuLayer = [[CCLayer alloc] init];
        [self addChild:menuLayer];
        
        CCMenu *menu = [CCMenu menuWithItems: nil];
        
        
        NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
        NSData *dataRepresentingSavedArray = [currentDefaults objectForKey:@"Scores"];
        NSArray *objectArray;
        if (dataRepresentingSavedArray != nil)
        {
            NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
            if (oldSavedArray != nil)
                objectArray = [[NSMutableArray alloc] initWithArray:oldSavedArray];
            else
                objectArray = [[NSMutableArray alloc] init];
            
            NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"level" ascending:YES];
        
            [objectArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];
        
            for (Score *score in objectArray){
                CCMenuItem *item = [CCMenuItemFont itemFromString: [[NSString alloc] initWithFormat:@"Level %@ - %@ (%@)", score.level, score.score, score.playerName]];
                [menu addChild: item];
            }
        }
        
        CCMenuItem *backItem = [CCMenuItemFont itemFromString:@"Back" target:self selector:@selector(back:)];
        [menu addChild:backItem];
        [menu alignItemsVertically];
        [menuLayer addChild: menu];
        
        
    }
    return self;
}
- (void) back: (id) sender
{
    [[CCDirector sharedDirector] replaceScene:[MainMenuScene scene]];
}

- (void) dealloc
{
    
    [super dealloc];
}

@end

